#ifndef _LOG_BILL_H_
#define _LOG_BILL_H_

#include <iostream>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

using namespace std;

//log 文件默认大小
const long	LOG_DEFAULT_SIZE	= 500000;
//log 文件默认最大数量
const int 	LOG_FILE_NUM		= 1000;

typedef enum _log_level_
{
	LM_ALL		= 0,
	LM_TRACE	= 1,
	LM_DEBUG	= 2,
	LM_WARNING	= 3,
	LM_INFO		= 4,
	LM_ERROR	= 5,
	LM_FATAL	= 6,
	LM_NONE		= 10
}loglevel_t;

typedef struct
{
	int fd;
	int seq;
	int day;
}LOG_FILE_INFO;

#define LOG_DEFAULT(lvl, fmt, args...)		APIlogwrite(lvl, fmt, ##args)
#define trace_log(fmt, args...)				LOG_DEFAULT(LM_TRACE, fmt, ##args)	
#define debug_log(fmt, args...)				LOG_DEFAULT(LM_DEBUG, fmt, ##args)	
#define warning_log(fmt, args...)			LOG_DEFAULT(LM_WARNING, fmt, ##args)	
#define info_log(fmt, args...)				LOG_DEFAULT(LM_INFO, fmt, ##args)	
#define error_log(fmt, args...)				LOG_DEFAULT(LM_ERROR, fmt, ##args)	
#define fatal_log(fmt, args...)				LOG_DEFAULT(LM_ERROR, fmt, ##args)	

extern int createdir(const char *path);
extern int APIlogwrite(loglevel_t loglevel, const char *fmt, ...);

class log_bill
{
	public:
		~log_bill();
		static log_bill *instance();

	public:
		int init(loglevel_t loglevel, const char *logdir, const char *logname, int logsize);
		int writelog(loglevel_t loglevel, const char *fmt, ...);
		int vwritelog(loglevel_t loglevel, const char *fmt, va_list ap);

	private:
		int shiftlogfiles(struct tm &stm);
		int openfile(struct tm &stm);
		int getfilename(char *logfile, int len);

	private:
		log_bill();
		static log_bill *m_instance;

	private:
		char 	m_logdir[128];
		char 	m_logname[16];
		int 	m_logsize;
		loglevel_t 		m_loglevel;
		LOG_FILE_INFO 	m_logfile;
		pthread_mutex_t m_mutex;
};

#endif

